package li.controller;

import java.util.Set;

import javax.servlet.http.HttpSession;

import li.entity.Book;
import li.entity.User;
import li.service.HomeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
	@Autowired
	private HomeService homeService;

	@RequestMapping({ "/", "/index" })
	public String index() {
		return "index";
	}

	@RequestMapping("/book")
	public String book(Model m) {
		m.addAttribute("hotBooks", homeService.findHotBooks());
		return "book";
	}

	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public String userDetail(String username, String password, Model m,
			HttpSession session) {
		User u = homeService.ValidateUser(username, password);
		if (u == null) {
			m.addAttribute("tip", "账户或密码错误");
			return "user";
		}
		Set<Book> books = homeService.findUserBooks(u.getId());
		u.setBooks(books);
		session.setAttribute("user", u);
		m.addAttribute("books", books);
		return "user_detail";
	}

	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String user(HttpSession session, Model m) {
		User u = (User) session.getAttribute("user");
		if (u == null) {
			// 如果session中没有user对象，即没有登录
			return "user";
		}
		// 如果已经登陆过了
		return "user_detail";
	}

	@RequestMapping(value = "/book/return/{id}", method = RequestMethod.GET)
	public String returnBook(@PathVariable long id, Model m, HttpSession s) {
		User u = (User) s.getAttribute("user");
		homeService.returnBook(id, u);
		return "user_detail";
	}

	@RequestMapping(value = "/book/borrow/{id}", method = RequestMethod.GET)
	public String borrowBook(@PathVariable long id, Model m, HttpSession s) {
		User u = (User) s.getAttribute("user");
		if (u == null) {
			return "user";
		}
		homeService.borrowBook(id, u);
		return "user_detail";
	}

	@RequestMapping("/book/{id}")
	public String bookDetail(@PathVariable long id, Model m) {
		Book b = homeService.findOneBook(id);
		m.addAttribute("book", b);
		return "book_detail";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession s) {
		s.removeAttribute("user");
		return "user";
	}

	@RequestMapping(value = "/signUp", method = RequestMethod.POST)
	public String signUp2(HttpSession s, String username, String password,
			String stuId) {
		try {
			homeService.createNewUser(username, password, stuId);
		}
		catch (Exception e) {
			return "signUp";
		}
		return "user";
	}

	@RequestMapping(value = "/signUp", method = RequestMethod.GET)
	public String signUp(HttpSession s) {
		return "signUp";
	}
}
